package com.example.demo.testso.utils;

import org.java_websocket.WebSocket;
import org.java_websocket.handshake.ClientHandshake;
import org.java_websocket.server.WebSocketServer;

import javax.websocket.Session;
import java.net.InetSocketAddress;
import java.util.ArrayList;
import java.util.List;

//websocket工具
public class WebSocketUtil extends WebSocketServer {
    private static List<WebSocket> webSocketArrayList = new ArrayList<WebSocket>();

    public WebSocketUtil(int port) {
        super(new InetSocketAddress(port));
    }

    @Override
    public void onOpen(WebSocket webSocket, ClientHandshake clientHandshake) {
        webSocketArrayList.add(webSocket);
        System.out.println("上线一个："+webSocket.getRemoteSocketAddress().getHostName());
    }

    @Override
    public void onClose(WebSocket webSocket, int i, String s, boolean b) {
        webSocketArrayList.remove(webSocket);
        System.out.println("下线一个："+webSocket.getRemoteSocketAddress().getHostName());
    }

    @Override
    public void onMessage(WebSocket ws, String s) {
        System.out.println("收到消息：" + s);
        //收到什么消息，回复什么
        ws.send(s);

        if (ws.isClosed()) {
        } else if (ws.isClosing()) {
            System.out.println("ws连接正在关闭...");
        } else if (ws.isConnecting()) {
            System.out.println("ws正在连接中...");
        } else if (ws.isOpen()) {
            System.out.println("ws连接已打开...");
            System.out.println(s);
        }

    }

    @Override
    public void onError(WebSocket webSocket, Exception e) {

    }

    @Override
    public void onStart() {
        System.out.println("------------------onStart-------------------");
    }


    public static List<WebSocket> getWebSocketArrayList() {
        return webSocketArrayList;
    }

    public static void setWebSocketArrayList(List<WebSocket> webSocketArrayList) {
        WebSocketUtil.webSocketArrayList = webSocketArrayList;
    }

    public static void sendMessage(String msg) {
        for (WebSocket webSocket : webSocketArrayList) {
            webSocket.send(msg);
        }
        System.out.println("发送消息：" + msg);
    }

}
